package com.wcq.studentbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wcq.studentbackend.entity.AdminUser;
import com.wcq.studentbackend.entity.Student;
import com.wcq.studentbackend.mapper.AdminUserMapper;
import com.wcq.studentbackend.mapper.StudentMapper;
import com.wcq.studentbackend.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final AdminUserMapper adminUserMapper;
    private final StudentMapper studentMapper;

    @Autowired
    public UserDetailsServiceImpl(AdminUserMapper adminUserMapper, StudentMapper studentMapper) {
        this.adminUserMapper = adminUserMapper;
        this.studentMapper = studentMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String usernameWithRole) throws UsernameNotFoundException {
        log.debug("开始加载用户: {}", usernameWithRole);
        
        if (usernameWithRole == null || !usernameWithRole.contains(":")) {
            throw new UsernameNotFoundException("用户名或角色格式不正确: " + usernameWithRole);
        }

        String[] parts = usernameWithRole.split(":", 2);
        String role = parts[0];
        String identifier = parts[1];
        log.debug("解析用户信息 - 角色: {}, 标识符: {}", role, identifier);

        List<GrantedAuthority> authorities = new ArrayList<>();
        String dbPasswordHash;
        String returnUsername;

        if ("admin".equalsIgnoreCase(role)) {
            AdminUser adminUser = adminUserMapper.selectOne(new QueryWrapper<AdminUser>().eq("username", identifier));
            if (adminUser == null) {
                throw new UsernameNotFoundException("管理员用户未找到: " + identifier);
            }
            dbPasswordHash = adminUser.getPassword();
            returnUsername = adminUser.getUsername();
            authorities.add(new SimpleGrantedAuthority("ROLE_" + adminUser.getRole().toUpperCase()));
            log.debug("找到管理员用户: {}, 密码哈希: {}", returnUsername, dbPasswordHash);
            
            if (!PasswordUtil.isValidBCryptFormat(dbPasswordHash)) {
                log.debug("管理员密码不是BCrypt格式，进行加密");
                dbPasswordHash = PasswordUtil.encode(dbPasswordHash);
                adminUser.setPassword(dbPasswordHash);
                adminUserMapper.updateById(adminUser);
            }

        } else if ("student".equalsIgnoreCase(role)) {
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("stu_no", identifier));
            if (student == null) {
                throw new UsernameNotFoundException("学生用户未找到: " + identifier);
            }
            
            // 更新学生密码为新的加密值
            if ("password123".equals(student.getPassword())) {
                dbPasswordHash = "$2a$10$qQaoxb3tghB31bl844hINexNMr0VHrCA2z8dZBuHGUL0RjTKvvv2i";
                student.setPassword(dbPasswordHash);
                studentMapper.updateById(student);
                log.debug("已更新学生密码为新的加密值");
            } else {
                dbPasswordHash = student.getPassword();
            }
            
            returnUsername = student.getStuNo();
            authorities.add(new SimpleGrantedAuthority("ROLE_" + student.getRole().toUpperCase()));
            log.debug("找到学生用户: {}, 密码哈希: {}", returnUsername, dbPasswordHash);
            
            if (!PasswordUtil.isValidBCryptFormat(dbPasswordHash)) {
                log.debug("学生密码不是BCrypt格式，进行加密");
                dbPasswordHash = PasswordUtil.encode(dbPasswordHash);
                student.setPassword(dbPasswordHash);
                studentMapper.updateById(student);
            } else {
                log.debug("验证密码格式 - 长度: {}, 前缀: {}", 
                    dbPasswordHash.length(), 
                    dbPasswordHash.substring(0, Math.min(7, dbPasswordHash.length())));
            }
        } else {
            throw new UsernameNotFoundException("不支持的用户角色: " + role);
        }
        
        if (dbPasswordHash == null || dbPasswordHash.isEmpty()) {
            throw new UsernameNotFoundException("用户密码不能为空");
        }

        log.debug("创建UserDetails对象 - 用户名: {}, 密码哈希: {}, 权限: {}", 
            returnUsername, dbPasswordHash, authorities);

        return User.builder()
            .username(returnUsername)
            .password(dbPasswordHash)
            .authorities(authorities)
            .accountExpired(false)
            .accountLocked(false)
            .credentialsExpired(false)
            .disabled(false)
            .build();
    }
} 